import {createWebHistory,createRouter} from 'vue-router'
import { getCurrentUserRole } from '@/utils/auth';

const routes = [
    {
        path:'/',
        redirect:'/login'
    },
    {
        path:'/login',
        name:'login',
        component: () => import('@/page/Login/index.vue'),
        children: [
            {
                path:'',
                redirect:'/log'
            },
            {
                path:'/log',
                name:'log',
                component: () => import('@/page/Login/components/Log.vue')
            },
            {
                path:'/register',
                name:'register',
                component: () => import('@/page/Login/components/Register.vue')
            }
        ]
    },
    {
        path:'/home',
        name:'home',
        component: () => import('@/page/Home/index.vue'),
        meta: {
            requireAuth: true,
            requiresHome: true
        }
    },
    {
        path:'/user-center',
        name:'user-center',
        component: () => import('@/page/UserCenter/index.vue'),
    },
    {
        path:'/appointment',
        name:'appointment',
        component: () => import('@/page/appointment/index.vue'),
    },
    {
        path:'/admin',
        name:'admin',
        component: () => import('@/page/admin/index.vue'),
        meta: {
            requiresAdmin: true
        }
    }   
]

// 检查是否登录
const isAuth = ()=>{
    return !!sessionStorage.getItem('auth')
}

const router = createRouter({
    history:createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    const userRole = getCurrentUserRole();

    if (to.meta.requiresAdmin && userRole !== 'admin') {
        next('/home');
    } else if (to.meta.requiresHome && userRole === 'admin') {
        next('/admin');
    } 
    // 遍历跳转的路由以及子路由，检测是否有需要验证的
    if (to.matched.some(record => record.meta.requireAuth)) {
      // 该路由需要登录
      if (!isAuth()) {
        // 未登录，跳转到登录页面
        next({ name:'log' })
      } else {
        // 已登录，继续访问
        next()
      }
    } 
    // 已登录用户试图访问登录页面时，重定向到主页
    else if (to.path === '/log' && isAuth()) {
      next({ path: '/home' });
    } 
    // 不需要验证的页面
    else {
      next()
    }
})


export default router